<template>
  <a-card :title="title">
    <div slot="extra" class="drawer-bootom-button">
      <!-- <a-dropdown :trigger="['click']" placement="topCenter">
        <a-menu slot="overlay">
          <a-menu-item key="4" @click="handleAdd('root')">添加根节点</a-menu-item>
          <a-menu-item key="5" @click="expandAll">展开所有</a-menu-item>
          <a-menu-item key="6" @click="closeAll">合并所有</a-menu-item>
        </a-menu>
        <a-button>
          树操作
          <a-icon type="up"/>
        </a-button>
      </a-dropdown> -->
      <a-button type="primary" @click="handleAdd('root')"> 新建模型 </a-button>
    </div>
    <div style="background: #fff">
      <a-col :md="10" :sm="24">
        <template>
          <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
            <span style="user-select: none">
              <a-tree
                :show-line="true"
                @select="onSelect"
                @check="onCheck"
                @rightClick="rightHandle"
                :replaceFields="{ children: 'children', title: 'modelName', key: 'id' }"
                :selectedKeys="selectedKeys"
                :checkedKeys="checkedKeys"
                :treeData="departTree"
                :checkStrictly="checkStrictly"
                :expandedKeys="iExpandedKeys"
                :autoExpandParent="autoExpandParent"
                @expand="onExpand"
              >
                <a-icon slot="switcherIcon" type="down" />
              </a-tree>
            </span>
            <!--新增右键点击事件,和增加添加和删除功能-->
            <a-menu slot="overlay">
              <!-- <a-menu-item @click="handleAdd()" key="1">添加节点</a-menu-item> -->
              <a-menu-item @click="handleEdit" key="2">编辑模型</a-menu-item>
              <a-menu-item @click="handleDelete" key="3">删除模型</a-menu-item>
              <a-menu-item @click="closeDrop" key="4">取消操作</a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </a-col>
    </div>
    <addTreeNode ref="addTreeNode" @ok="loadData"></addTreeNode>
  </a-card>
</template>

<script>
import { getAction, deleteAction, httpAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import addTreeNode from './addTreeNode'

export default {
  name: 'LeftTree',
  props: ['id', 'type', 'title', 'isload'],
  mixins: [JeecgListMixin],
  components: { addTreeNode },
  data() {
    return {
      rightClickSelectedKey: '',
      rightClickSelectedNode: '',
      dropTrigger: '',
      iExpandedKeys: [],
      loading: false,
      autoExpandParent: true,
      currFlowId: '',
      currFlowName: '',
      treeData: [],
      departTree: [],
      hiding: true,
      checkedKeys: [],
      selectedKeys: [],
      currSelected: {},
      allTreeKeys: [],
      checkStrictly: true,
      url: '/metaDataModel/modelList',
      orgCategoryDisabled: false,
    }
  },
  watch: {
    isload: {
      handler(val) {
        this.loadTree()
      },
    },
  },
  methods: {
    loadData() {
      this.refresh()
    },
    handleAdd(root) {
      if (root === 'root') {
        this.$refs.addTreeNode.add(this.id)
      } else {
        this.$refs.addTreeNode.add(this.rightClickSelectedNode)
      }
    },
    handleEdit() {
      this.$refs.addTreeNode.edit(this.rightClickSelectedNode)
    },
    handleDelete() {
      this.$confirm({
        title: '确认删除',
        content: '确定要删除此模型以及子节点数据吗?',
        onOk: () => {
          // deleteAction('/metaDataModel/delMetaDataModel', { id: this.rightClickSelectedNode.id }).then((res) => {
          //   if (res.success) {
          //     this.$message.success('删除成功!')
          //     this.loadTree()
          //   }
          // })
          // debugger
          httpAction('/metaDataModel/delMetaDataModel', { id: this.rightClickSelectedNode.id }, 'delete').then(
            (res) => {
              if (res.success) {
                this.$message.success(res.message)
                this.loadTree()
              } else {
                this.$message.error(res.message)
              }
            }
          )
        },
      })
    },
    // 右键点击下拉框改变事件
    dropStatus(visible) {
      if (visible == false) {
        this.dropTrigger = ''
      }
    },
    // 右键下拉关闭下拉框
    closeDrop() {
      this.dropTrigger = ''
    },
    rightHandle(node) {
      this.dropTrigger = 'contextmenu'
      this.rightClickSelectedKey = node.node.eventKey
      this.rightClickSelectedNode = node.node.dataRef
    },
    loadTree() {
      var that = this
      that.treeData = []
      that.departTree = []
      //   , { proId: this.id, typeId: this.type }
      getAction(this.url).then((res) => {
        if (res.success) {
          //部门全选后，再添加部门，选中数量增多
          this.allTreeKeys = []
          this.$emit('getTree', res.result)
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            that.treeData.push(temp)
            that.departTree.push(temp)
            that.setThisExpandedKeys(temp)
            that.getAllKeys(temp)
            // console.log(temp.id)
          }
          // TODO 第一次选择第一个
          this.selectedKeys = [this.treeData[0].id]
          let Arr = res.result
          if (this.selectedKeys.length) {
            for (let item of Arr) {
              if (item.id === this.selectedKeys[0]) {
                this.$emit('selected', item)
              }
            }
          }
          this.loading = false
        }
      })
    },
    setThisExpandedKeys(node) {
      if (node.children && node.children.length > 0) {
        this.iExpandedKeys.push(node.key)
        for (let a = 0; a < node.children.length; a++) {
          this.setThisExpandedKeys(node.children[a])
        }
      }
    },
    refresh() {
      this.loading = true
      this.loadTree()
    },
    onExpand(expandedKeys) {
      console.log('onExpand', expandedKeys)
      this.iExpandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    nodeModalOk() {
      this.loadTree()
    },
    nodeModalClose() {},
    onCheck(checkedKeys, info) {
      console.log('onCheck', checkedKeys, info)
      this.hiding = false
      //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
      if (this.checkStrictly) {
        this.checkedKeys = checkedKeys.checked
      } else {
        this.checkedKeys = checkedKeys
      }
      //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
    },
    onSelect(selectedKeys, e) {
      console.log('selected', selectedKeys, e)
      this.hiding = false
      let record = e.node.dataRef
      console.log('onSelect-record', record)
      this.currSelected = Object.assign({}, record)
      this.selectedKeys = [record.id]
      this.$emit('selected', this.currSelected)
    },
    getCurrSelectedTitle() {
      return !this.currSelected.title ? '' : this.currSelected.title
    },
    onClearSelected() {
      this.hiding = true
      this.checkedKeys = []
      this.currSelected = {}
      this.selectedKeys = []
      this.$refs.departAuth.departId = ''
    },
    //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
    expandAll() {
      this.iExpandedKeys = this.allTreeKeys
    },
    closeAll() {
      this.iExpandedKeys = []
    },
    getAllKeys(node) {
      // console.log('node',node);
      this.allTreeKeys.push(node.key)
      if (node.children && node.children.length > 0) {
        for (let a = 0; a < node.children.length; a++) {
          this.getAllKeys(node.children[a])
        }
      }
    },
    //---- author:os_chengtgen -- date:20190827 --  for:切换父子勾选模式 =======------
  },
}
</script>

<style lang="less" scoped>
.ant-card {
  height: 100%;

  /deep/ .ant-card-head {
    padding: 0 15px;

    /deep/ .ant-card-head-title,
    /deep/ .ant-card-extra {
      padding: 10px 0;
    }
  }

  /deep/ .ant-card-body {
    padding: 10px;
    height: calc(100vh - 450px);
    overflow: auto;
  }
}
</style>